<!-- src/components/CreateBucketDrawer.vue (最终修复版) -->
<template>
    <!-- 唯一的、正确的 el-drawer -->
    <el-drawer :model-value="visible" title="创建 Bucket" direction="rtl" size="900px" @update:model-value="handleClose"
        @closed="resetCreateForm">
        <!-- Drawer 的主内容区 -->
        <div class="create-bucket-drawer-content">
            <!-- 直接放置 el-form -->
            <el-form ref="createFormRef" :model="createForm" :rules="createFormRules" label-position="top">

                <!-- ========【核心修改 1：使用卡片进行视觉分组】======== -->
                <el-card shadow="never" class="form-section-card">
                    <template #header>
                        <div class="card-header">基础信息</div>
                    </template>

                    <el-form-item label="Bucket 名称" prop="bucketName">
                        <el-input v-model="createForm.bucketName" placeholder="3-63位，只能包含小写字母、数字和连字符(-)" maxlength="63"
                            show-word-limit />
                    </el-form-item>

                    <el-form-item label="地域" prop="region">
                        <el-select v-model="createForm.region" placeholder="请选择地域" style="width: 100%;" disabled>
                            <el-option label="福建-智汇云" value="fujian-zhihcs"></el-option>
                        </el-select>
                        <div class="form-item-tip">注意：创建成功后地域将无法更改。</div>
                    </el-form-item>
                </el-card>

                <el-card shadow="never" class="form-section-card">
                    <template #header>
                        <div class="card-header">Bucket 功能</div>
                    </template>

                    <el-form-item label="读写权限 (ACL)" prop="acl">
                        <el-radio-group v-model="createForm.acl">
                            <el-radio value="private">私有</el-radio>
                            <el-radio value="public-read">公共读</el-radio>
                            <el-radio value="public-read-write">公共读写</el-radio>
                        </el-radio-group>
                        <!-- ========【核心修改 2：动态描述】======== -->
                        <div class="form-item-tip">{{ aclDescription }}</div>
                    </el-form-item>

                    <el-form-item label="版本控制">
                        <div class="versioning-control">
                            <el-switch v-model="createForm.versioning" />
                            <el-text type="info" size="small" class="versioning-tip">
                                开启后无法关闭，仅支持暂停。未开启版本控制，删除数据将无法恢复。
                            </el-text>
                        </div>
                    </el-form-item>
                </el-card>

            </el-form>
        </div>

        <!-- Drawer 的页脚部分 -->
        <template #footer>
            <!-- 【重要】将按钮放在一个普通的 div 中，它就会默认左对齐 -->
            <div class="drawer-footer">
                <el-button type="primary" :loading="isCreating" @click="submitCreate">完成创建</el-button>
                <el-button @click="handleClose">取消</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';

// 1. 定义 props 和 emits
const props = defineProps({
    visible: {
        type: Boolean,
        required: true,
    },
});
const emit = defineEmits(['update:visible', 'create-success']);

// 2. 所有表单相关的 ref 和 reactive
const isCreating = ref(false);
const createFormRef = ref(null);

// 表单数据模型
const createForm = reactive({
    bucketName: '',
    region: 'fujian-zhihcs', // 默认值
    storageClass: 'Standard',
    redundancyType: 'ZRS',
    acl: 'private',
    versioning: false,
});

// 表单校验规则
const createFormRules = reactive({
    bucketName: [
        { required: true, message: '请输入 Bucket 名称', trigger: 'blur' },
        { min: 3, max: 63, message: '长度在 3 到 63 个字符', trigger: 'blur' },
        {
            pattern: /^[a-z0-9][a-z0-9-]*[a-z0-9]$/,
            message: "只能包含小写字母、数字和连字符(-)，且不能以'-'开头或结尾",
            trigger: 'blur'
        },
        {
            pattern: /^(?!.*--).*$/,
            message: "不能包含连续的连字符(--)",
            trigger: 'blur'
        },
    ],
    region: [
        { required: true, message: '请选择地域', trigger: 'change' }
    ],
    storageClass: [
        { required: true, message: '请选择存储类型', trigger: 'change' }
    ],
    redundancyType: [
        { required: true, message: '请选择存储冗余类型', trigger: 'change' }
    ],
    acl: [
        { required: true, message: '请选择读写权限', trigger: 'change' }
    ],
});

const aclDescriptionMap = {
    'private': '私有：对文件的所有访问都需要进行身份验证。',
    'public-read': '公共读：任何人（包括匿名用户）都可以读取文件，但只有所有者有写入权限。',
    'public-read-write': '（高风险）公共读写：任何人都可以读、写、删除文件，请谨慎使用。'
};

const aclDescription = computed(() => aclDescriptionMap[createForm.acl]);

// 3. 定义组件内部方法
const handleClose = () => {
    emit('update:visible', false);
};

const resetCreateForm = () => {
    if (createFormRef.value) {
        createFormRef.value.resetFields();
    }
};

const submitCreate = async () => {
    if (!createFormRef.value) return;
    await createFormRef.value.validate(async (valid) => {
        if (valid) {
            isCreating.value = true;
            try {
                // 将表单数据发送给后端
                await apiClient.post('/api/v1/buckets', {
                    bucket_name: createForm.bucketName,
                    region: createForm.region,
                    acl: createForm.acl,
                    versioning: createForm.versioning,
                    storage_class: createForm.storageClass,
                    redundancy_type: createForm.redundancyType,
                });
                ElMessage.success(`存储桶 '${createForm.bucketName}' 创建成功！`);
                emit('create-success');
                handleClose();
            } catch (error) {
                ElMessage.error(error.response?.data?.error || '创建失败');
            } finally {
                isCreating.value = false;
            }
        }
    });
};
</script>

<style scoped>
/* 所有相关的 CSS */
.create-bucket-drawer-content {
    padding: 0 20px;
    height: 100%;
    overflow-y: auto;
}

.form-section-card {
    margin-bottom: 24px;
}

.form-section-card :deep(.el-card__header) {
    padding: 12px 20px;
    background-color: #f7f9fc;
}

.card-header {
    font-size: 16px;
    font-weight: 500;
}

.form-item-tip {
    color: #909399;
    font-size: 12px;
    line-height: 1.5;
    margin-top: 4px;
    margin-left: 20px;
}

.versioning-control {
    display: flex;
    align-items: center;
}

.versioning-tip {
    margin-left: 12px;
}

/* 页脚样式 */
.drawer-footer {
    display: flex;
    gap: 12px;
}

/* 优化 radio-group 间距 */
.el-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 20px;
    /* 垂直间距8px，水平间距20px */
}

.el-radio-group .el-radio {
    margin-right: 0;
    /* 移除默认的margin，让gap生效 */
}
</style>